/**
 * 缓存页面
 * 利用 keep-alive 缓存页面， 缓存的字段为路由 name 字段
 */
import { defineStore } from 'pinia'
import store from '@/store'

interface KeepAliveStateProps {
  cacheList: Array<string> // 缓存列表
  visitedList: Array<string> // 缓存记录
}
export const useKeepAliveStore = defineStore('keep-alive', {
  state: ():KeepAliveStateProps => {
    return {
      cacheList: [],
      visitedList: []
    }
  },
  actions: {
    // 添加缓存页面
    addCachePage (name:string) {
      if (!this.cacheList.includes(name) && !!name) {
        this.cacheList.push(name)
      }
    },

    // 删除缓存页面
    delCachePage (name:string) {
      const list = this.cacheList
      for (let i = 0; i < list.length; i++) {
        if (list[i] === name) {
          list.splice(i, 1)
          return
        }
      }
    },

    // 重置缓存记录
    resetVisited () {
      this.visitedList = []
    },

    // 删除缓存记录
    delVisited (name:string) {
      const list = this.visitedList
      for (let i = 0; i < list.length; i++) {
        if (list[i] === name) {
          list.splice(i, 1)
          return
        }
      }
    },

    // 添加缓存记录
    addVisited (name:string) {
      if (!name) return
      this.visitedList.push(name)
    }
  },
  persist: {
    storage: sessionStorage
  }
})

export default useKeepAliveStore

// 在组件外使用
export function useKeepAliveStoreOutside () {
  return useKeepAliveStore(store)
}
